package it.com.Test.a1_async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestOfHandle {

    static ExecutorService executor = Executors.newFixedThreadPool(3);

    /*
    感知到异常后直接处理
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 有返回值
        System.out.println("main....start....");
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
//             int i = 10 / 0;
            System.out.println("异步任务睡眠3s");
             try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println("运行结果：" + i);
            return i;
        }, executor).handle((r, e) -> {
            // 返回默认值
            if(e != null) {
                return 0;
            } else {
                return r;
            }
        });
        // 在获取到结果之前会一直阻塞
        System.out.println("异步任务返回值：" + completableFuture.get());
        System.out.println("main....end....");
/**
 main....start....
 当前线程：12
 运行结果：5
 main....end....5
 ----------------------------------------------------
 main....start....
 当前线程：12
 main....end....0
  */

    }
}
